<template>
    <div class="one-organization-analysis" v-loading="loading">
        <!-- 单个组织部门分析 -->
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item>
                    <!-- 选择ums组织-->
                    <tree-select
                        v-model="searchForm.orgIds"
                        filterable
                        :width="200"
                        :data="orgOptions"
                        :defaultProps="orgDefaultProps"
                        :checkedKeys="defaultCheckedOrgIds"
                        :nodeKey="orgNodeKey"
                        @popoverHide="orgPopoverHide">
                    </tree-select>
                </el-form-item>
                <el-form-item>
                    <!-- 选择部门-->
                    <tree-select
                        placeholder="请选择部门"
                        v-model="searchForm.deptId"
                        filterable
                        :width="200"
                        :data="deptOptions"
                        :defaultProps="deptDefaultProps"
                        :checkedKeys="defaultCheckedDeptIds"
                        :nodeKey="deptNodeKey"
                        @popoverHide="deptPopoverHide">
                    </tree-select>
                </el-form-item>
                <el-form-item >
                    <!-- 日期范围 -->
                    <el-date-picker
                        v-model="searchForm.time"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        :picker-options="utils.intTimePickerOptions()"
                        @change="search">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row v-show="hasDepartmentData">
            <el-col :span="24">
                <h3 class="text-center">{{ orgName }}-{{ deptName }}</h3>
            </el-col>
        </el-row>
        <!-- 场次统计 -->
        <p class="model-title" v-show="hasDepartmentData">参加考试情况</p>
        <el-row class="exam-num-count-wrap" v-show="hasDepartmentData">
            <el-col :span="24">
                <el-row class="overview-wrap" type="flex">
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-4">{{ takeTestInfo.examCount }}场</p>
                            <p class="item-title">应参考场次</p>
                        </div>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="12">
                <el-row class="overview-wrap exam-num-count-list" type="flex" justify="space-between">
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-4">{{ takeTestInfo.examPeolpleCount }}人次</p>
                            <p class="item-title">应参考人次</p>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-3">{{ takeTestInfo.actualExamPeolpleCount }}人次</p>
                            <p class="item-title">实际参考人次</p>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-2">{{ takeTestInfo.lackExamPeolpleCount }}人次</p>
                            <p class="item-title">缺考人次</p>
                        </div>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="12">
                <div id="takeTestCountEchart" class="echart-wrap"></div>
            </el-col>
        </el-row>
        <!-- 场次统计 -->
        <p class="model-title" v-show="hasDepartmentData">考生得分排名</p>
        <el-row v-show="hasDepartmentData">
            <el-col :span="24">
                <el-form class="department-serach-form" ref="searchForm2" :model="searchForm2" :inline="true" @submit.native.prevent>
                    <el-form-item>
                        <!-- 选择考试场次 -->
                        <el-select filterable @change="getExamineeScoreSort" v-model="searchForm2.examId" placeholder="请选择考试场次">
                            <el-option
                                v-for="item in examOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button class="form-search-btn" type="primary" @click="getExamineeScoreSort">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row v-show="hasDepartmentData && hasExamSortInfo">    
            <el-col :span="24">
                <div class="examinee-score-distributed-wrap">
                    <p class="echart-title text-center">考生得分排名</p>
                    <P class="text-center">
                        <el-radio-group v-model="searchForm2.sortType" @change="getExamineeScoreSort">
                            <el-radio-button label='asc'>正排</el-radio-button>
                            <el-radio-button label='desc'>倒排</el-radio-button>
                        </el-radio-group>
                    </P>
                    <div id="deptExamineeScoreSortEchart" class="echart-wrap"></div>
                </div>
            </el-col>
        </el-row>
        <!-- 暂无数据 -->
        <div v-if="hasDepartmentData && !hasExamSortInfo" class="no-data">
            <p class="no-data-text">暂无考试数据</p>
        </div>
        <!-- 考试明细 -->
        <el-row v-if="hasDepartmentData">
            <el-col :span="20">
                <p class="model-title">考试明细</p>
            </el-col>
            <el-col :span="4">
                <el-row type="flex" justify="end">
                    <el-button type="primary" @click="exportDetail">导出明细</el-button>
                </el-row>
            </el-col>
        </el-row>
        <el-row v-if="hasDepartmentData">
            <el-col :span="24">
                <el-row type="flex" class="type-item-wrap">
                    <el-col :span="24" class="exam-detail-table">
                        <el-table
                            v-loading="loading"
                            border
                            ref="examDetailTable"
                            :data="tableData"
                            style="width: 100%">
                            <el-table-column label="序号" type="index" width="50"></el-table-column>
                            <el-table-column label="考试名称" prop="examName"></el-table-column>
                            <el-table-column label="组织" prop="organization"></el-table-column>
                            <el-table-column label="部门" prop="department"></el-table-column>
                            <el-table-column label="职位" prop="postName"></el-table-column>
                            <el-table-column label="考生" prop="examAccountName"></el-table-column>
                            <el-table-column label="答题开始时间" prop="beginTime"></el-table-column>
                            <el-table-column label="耗时" prop="costTime"></el-table-column>
                            <el-table-column label="得分" prop="score"></el-table-column>
                            <el-table-column label="排名" prop="ranking">
                                <template slot-scope="scope">
                                    <p v-if="scope.row.status == 0">缺考</p>
                                    <p v-else-if="scope.row.status == 1">考试进行中</p>
                                    <p v-else>{{ scope.row.ranking }}</p>
                                </template>
                            </el-table-column>
                            <el-table-column label="答卷明细" width="100">
                                <template slot-scope="scope">
                                    <el-button v-if="scope.row.status == 2" @click="handleDetail(scope.row)" type="text" size="small">查看</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination
                            background
                            small
                            @current-change="handleCurrentChange"
                            @size-change="handleSizeChange"
                            :current-page.sync="currentPage"
                            :page-sizes="[10, 50, 100]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                        </el-pagination>
                    </el-col>
                </el-row>
        
            </el-col>
        </el-row>
        <!-- 考生答卷明细 -->
        <el-dialog
            :close-on-click-modal="false"
            title="答卷"
            width="1200px"
            top='10vh'
            v-if="dialogExamPaper"
            :visible.sync="dialogExamPaper"
            @close="closeExamPaper"
            v-dialogDrag>
            <examinee-answer-sheet-view :oldInfo="currentExamPaperInfo" :closeFun="closeExamPaper"></examinee-answer-sheet-view>
        </el-dialog>
        <!-- 暂无数据 -->
        <div v-if="!hasDepartmentData" class="no-data">
            <p class="no-data-text">暂无部门数据</p>
        </div>
    </div>
</template>
<script>
import utils from '@/utils/util'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getExamInfoByDept, getExamineeScoreSort, getExamRecords, getDeptExamCountDetail, getExamDetailForCalc, exportDeptExamCountDetail } from '@/api/exam'
import { getUcOrgList } from '@/api/sysConfig'
import { getDepartmentTree } from '@/api/department'
import ExamineeAnswerSheetView from '@/components/Examination/Common/ExamineeAnswerSheetView'

export default {
    name: 'OneOrganization',
    components: {
        TreeSelect,
        ExamineeAnswerSheetView
    },
    data() {
        return {
            loading: true,
            utils: utils,
            hasDepartmentData: false, // 有无部门数据
            hasExamSortInfo: false, // 有无考试信息
            orgOptions: [], // 单位下拉框
            // ums组织单位
            orgDefaultProps: {
                children: 'nodes',
                label: 'name',
                value: 'id'
            },
            defaultCheckedOrgIds:[],
            orgNodeKey: 'id',
            // 组织部门
            deptOptions: [],
            deptDefaultProps: {
                children: 'nodes',
                label: 'name',
                value: 'id'
            },
            defaultCheckedDeptIds:[],
            deptNodeKey: 'id',
            searchForm: {
                orgIds: '',
                deptId: '',
                time: '',
            },
            orgName: '',
            deptName: '',
            takeTestInfo: {}, // 参考情况
            searchForm2: {
                examId: '',
                sortType: 'asc' // 升序 asc 降序 desc
            },
            examOptions: [], // 考试下拉框数据
            tableData: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            currentExamPaperInfo: {},
            dialogExamPaper: false
        }
    },
    created() {
        // 获取单位下拉框数据
        this.getOrgList()
    },
    methods: {
        getOrgList() {
            let that = this
            getUcOrgList({
                type: 1
            }).then(res => {
                that.orgOptions = res.data
                that.$nextTick(() => {
                    // 默认选中第一个
                    that.searchForm.orgIds = res.data[0].id
                    // 获取选择的选项的中文名称
                    that.orgName = res.data[0].name
                    that.defaultCheckedOrgIds = String(res.data[0].id).split(',')
                    that.getDeptOptionsData(res.data[0].id)
                })
            })
        },
        // 获取组织部门数据
        getDeptOptionsData(checkedIds) {
            getDepartmentTree({
                orgId: checkedIds || this.$store.state.userinfo.org.id,
                orgIds: checkedIds || this.$store.state.userinfo.organizationIds
            }).then(res => {
                if(res.status === 200) {
                    this.deptOptions = res.data
                    if(res.data.length > 0) {
                        this.hasDepartmentData = true
                        // 默认选择第一个
                        this.searchForm.deptId = res.data[0].id
                        // 获取选择的选项的中文名称
                        this.deptName = res.data[0].name
                        this.$nextTick(() => {
                            this.defaultCheckedDeptIds = res.data[0].id.toString().split(',')
                            this.search()
                        })
                    } else {
                        // 暂无部门数据
                        this.hasDepartmentData = false
                    }
                }
                this.loading = false
            })
        },
        // 选择了用户所属组织/单位
        orgPopoverHide(checkedIds, checkedData) {
            // 用户所属组织选择值变化
            if(checkedIds && checkedIds !== this.searchForm.orgIds) {
                // 初始化组织部门数据
                this.searchForm.deptId = ''
                this.defaultCheckedDeptIds = []
                this.takeTestInfo = {}
                // 重新绑定组织部门下拉框数据
                this.getDeptOptionsData(checkedIds)
                // 获取选择的选项的中文名称
                this.orgName = checkedData.name
            }
        },
        // 选择了组织部门
        deptPopoverHide(checkedIds, checkedData) {
            // 用户所属组织选择值变化
            if(checkedIds && checkedIds !== this.searchForm.deptId) {
                // 获取选择的选项的中文名称
                this.deptName = checkedData.name
            }
        },
        search() {
            this.loading = true
            this.takeTestInfo = {}
            this.getTakeTestInfoData()
            this.getExamOptionsData()
            this.getTableData(1, 10)
        },
        // 获取参考情况信息
        getTakeTestInfoData() {
            let that = this
            getExamInfoByDept({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                deptId: that.searchForm.deptId
            }).then(res => {
                if(res.status === 200) {
                    that.takeTestInfo = res.data
                    that.renderTakeTestCountEchart(res.data)
                }
            })
        },
        // 渲染参考情况饼图
        renderTakeTestCountEchart(data) {
            // 基于准备好的dom，初始化echarts实例
            let $dom = document.getElementById('takeTestCountEchart')
            if($dom) {
                this.$echarts.init($dom).setOption({
                    color: ['#47CFAD', '#FFB32D'],
                    grid: {
                        left: '3%',
                        right: '3%',
                        top: '35px',
                        bottom: '30px'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    series: [
                        {
                            name:'考试情况',
                            type:'pie',
                            radius: ['0%', '82%'],
                            avoidLabelOverlap: false,
                            label: {
                                formatter: "{b}: {c}({d}%)",
                                emphasis: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '20',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                            labelLine: {
                                normal: {
                                    show: true
                                }
                            },
                            data:[
                                {value:data.actualExamPeolpleCount, name:'实际参考人次'},
                                {value:data.lackExamPeolpleCount, name:'缺考人次'}
                            ]
                        }
                    ]
                })
            }
            this.loading = false
        },
        // 获取考试场次信息
        getExamOptionsData() {
            let that = this
            getExamRecords({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                queryType: 0,
                status: -1
            }).then(res => {
                if(res.status === 200) {
                    this.examOptions = res.data
                    if(res.data.length > 0) {
                        this.hasExamSortInfo = true
                        // 默认选择第一场
                        this.searchForm2.examId = res.data[0].id
                        this.getExamineeScoreSort()
                    } else {
                        // 暂无考试信息
                        this.hasExamSortInfo = false
                    }
                }
            })
        },
        // 获取考生得分排名统计
        getExamineeScoreSort() {
            getExamDetailForCalc({
                examInfoId: this.searchForm2.examId,
                departId: this.searchForm.deptId,
                sort: this.searchForm2.sortType
            }).then(res => {
                if(res.status === 200) {
                    this.renderExamineeScoreSortEchart(res.data)
                }
            })
        },
        // 渲染考生得分排名柱状图
        renderExamineeScoreSortEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data, (i, obj)=>{
                xData.push(obj.examAccountName)
                yData.push({
                    value: obj.score
                })
            })
            let option_echart = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return data.seriesName + '<br/>' + data.marker + data.name + '：' + data.value + '分'
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        },
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    name: '分数',
                    axisTick: {
                        show: false
                    },
                    min: 0,
                    max: 100,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "得分",
                    type: 'bar',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}%',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('deptExamineeScoreSortEchart')).setOption(option_echart, true)
        },
        // 获取列表数据
        getTableData(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            
            getDeptExamCountDetail({
                deptId: this.searchForm.deptId,
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize,
                queryType: 1
            }).then(res => {
                if(res.status === 200) {
                    that.tableData = res.data
                    that.total = res.total
                }
                that.loading = false
            })
            
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        // 导出明细
        exportDetail() {
            let that = this
            let parames = {
                deptId: that.searchForm.deptId,
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
            }
            let downloadUrl = this.GLOBAL.baseURL + 'exam/exportDeptExamCountDetail?startTime=' + parames.startTime +
                '&endTime=' + parames.endTime +
                '&deptId=' + parames.deptId

            window.open(downloadUrl)
        },
        // 查看答卷明细
        handleDetail(row) {
            this.currentExamPaperInfo = row
            this.dialogExamPaper = true
        },
        closeExamPaper() {
            this.dialogExamPaper = false
        }
    },
    computed: {
        deptIdChange() {
            return this.searchForm.deptId
        }
    },
    watch: {
        deptIdChange(val) {
            if(val) {
                this.search()
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.one-organization-analysis {
    .exam-num-count-wrap {
        .exam-num-count-list {
            padding-right: 20px;
            padding-bottom: 0;
            flex-direction: column;
            .el-col {
                margin: 10px 0;
            }
        }
        .echart-wrap {
            height: 463px;
        }
    }
}
</style>